package com.example.rightmost.service.Impl;

import com.example.rightmost.dao.CommentMapper;
import com.example.rightmost.entity.Comment;
import com.example.rightmost.entity.Result;
import com.example.rightmost.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author:javayhch
 * @date:2024/8/27
 * @description:
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    CommentMapper commentMapper;

    @Override
    public List<Comment> getCommentList(String text) {
        return commentMapper.getCommentList(text);
    }

    @Override
    public List<Comment> getCommentArea(Comment comment) {
        return commentMapper.getCommentArea(comment);
    }

    @Override
    public Result addComment(Comment comment) {
        comment.setCreateTime(LocalDateTime.now());
        int x = commentMapper.addComment(comment);
        if(x>0){
            return  Result.success();
        }else {
            return Result.error("false");
        }
    }

    @Override
    public Result addComment_2(Comment comment) {
        comment.setCreateTime(LocalDateTime.now());
        comment.setLevel('1');
        int x = commentMapper.addComment_2(comment);
        if(x>0){
            return  Result.success();
        }else {
            return Result.error("false");
        }
    }

    @Override
    public List<Comment> getCommentSonList(Comment comment) {
        return commentMapper.getCommentSonList(comment);
    }

    @Override
    public Map<Integer, List<Comment>> getCommentSon(Integer pieceId) {
        List<Comment> allCommentSon = commentMapper.getAllCommentSon(pieceId);
        Map<Integer, List<Comment>> commentSonMap = new HashMap<>();
        for (Comment comment: allCommentSon) {
            commentSonMap.put(comment.getParentCommentId(), new LinkedList<>());
        }
        for (Comment comment: allCommentSon) {
            List<Comment> comments = commentSonMap.get(comment.getParentCommentId());
            comments.add(comment);
            commentSonMap.put(comment.getParentCommentId(), comments);
        }
        return commentSonMap;
    }

    @Override
    public Result delete(Integer commentId) {
        Integer i = commentMapper.delete(commentId);
        if (i > 0){
            return Result.success();
        } else {
            return Result.error("删除失败");
        }
    }

}
